package io.chenglicun.common.trans.service.impl.db;

import io.chenglicun.common.entity.BaseEntity;
import io.chenglicun.common.trans.annotation.Trans;
import io.chenglicun.common.trans.core.TransField;
import io.chenglicun.common.trans.service.impl.TransRepository;
import io.chenglicun.common.trans.service.impl.db.driver.TransDriver;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class DbTransRepository implements TransRepository {

    @Resource
    private TransDriver transDriver;

    @Override
    public Map<String, Object> getTransValueMap(TransField transField, List<String> transValues) {
        List<? extends BaseEntity> entities = transDriver.findByIds(getIds(transValues), getEntity(transField.getField()));
        return entities.stream().collect(Collectors.toMap(x -> x.getId().toString(), x -> x));
    }

    /**
     * 获取查询id
     */
    private List<Long> getIds(List<String> transValues) {
        return transValues.stream()
                .map(Long::valueOf)
                .collect(Collectors.toList());
    }

    /**
     * 获取查询实体
     */
    private Class<? extends BaseEntity> getEntity(Field field) {
        Trans dbTrans = field.getAnnotation(Trans.class);
        return dbTrans.entity();
    }

}

